import * as React from 'react';

import * as StringHelper from '../MyHelper/StringHelper';
import * as Global from '../TS/Global';
import { MessageBox } from './messagebox';
import * as MyCfg from './MyCfg';
import { Service, ServiceState } from './Service';

export interface ServiceEvent {
    (msg: ServiceState, cmd?: string): boolean
}
export interface SerialProps extends Global.Myprops {
    ttxx?: string;
    //在数组的索引
    index?: number;
    serialcfg: MyCfg.Serial_cfg
};

interface SerialState {
    Isverifed?: boolean;

    SPath?: string;
    IsOn?: boolean;
    Baudrate?: string;
    Checkbit?: string;
    Databit?: string;
    Stopbit?: string;
    MaxLength?: string;
    MaxLength_check?: boolean;
    Interval?: string;
    Interval_check?: boolean;
    ServiceList?: MyCfg.Service_cfg[];
    SyncBaudrate?: boolean; //同步波特率 RFC2217
    ISHeartbeat?: boolean; //是否启用心跳包
    Heartbeat_Hex?: string; //心跳包字节                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    Heartbeat_Hex_check?: boolean;
    Heartbeat_Interval?: string; //心跳包间隔
    Heartbeat_Interval_check?: boolean;
    Is_FullDuplex?: false;
    Ismodbus?: boolean; //模式是否是modbus
    ModBuspoll_TimeOut?: string; //轮训时间间隔
    ModBuspoll_TimeOut_check?: boolean;
    ISCheck?: boolean;
};

export class Serial extends React.Component<SerialProps,
    SerialState> {
    constructor(props) {
        super(props);
        console.log(props.serialcfg);
        console.log(props.serialcfg.Ismodbus);
        //设置状态
        this.state = {

            Isverifed: true,
            SPath: props.serialcfg.SPath,
            IsOn: props.serialcfg.IsOn != undefined
                ? props.serialcfg.IsOn
                : false,
            Baudrate: props.serialcfg.IsOn
                ? props.serialcfg.Baudrate
                : '115200',
            Checkbit: props.serialcfg.Checkbit
                ? props.serialcfg.Checkbit
                : 'NONE',
            Databit: props.serialcfg.Databit
                ? props.serialcfg.Databit
                : '8',
            Stopbit: props.serialcfg.Stopbit
                ? props.serialcfg.Stopbit
                : '1',
            MaxLength: props.serialcfg.MaxLength
                ? props.serialcfg.MaxLength
                : '1024',

            Interval: props.serialcfg.Interval
                ? props.serialcfg.Interval
                : '20',
            SyncBaudrate: props.serialcfg.SyncBaudrate != undefined
                ? props.serialcfg.SyncBaudrate
                : false,
            ISHeartbeat: props.serialcfg.ISHeartbeat != undefined
                ? props.serialcfg.ISHeartbeat
                : false,
            Heartbeat_Hex: props.serialcfg.Heartbeat_Hex
                ? props.serialcfg.Heartbeat_Hex
                : "FF FF",
            Heartbeat_Interval: props.serialcfg.Heartbeat_Interval
                ? props.serialcfg.Heartbeat_Interval
                : '5000',
            Is_FullDuplex: props.serialcfg.Is_FullDuplex != undefined
                ? props.serialcfg.Is_FullDuplex
                : false,
            ServiceList: props.serialcfg.ServiceList
                ? props.serialcfg.ServiceList
                : [],
            Ismodbus: props.serialcfg.Ismodbus != undefined
                ? props.serialcfg.Ismodbus
                : false, //模式是否是modbus
            ModBuspoll_TimeOut: props.serialcfg
                ? props.serialcfg.ModBuspoll_TimeOut
                : '150', //轮训时间间隔
            MaxLength_check: true,
            Interval_check: true,
            Heartbeat_Hex_check: true,
            Heartbeat_Interval_check: true,
            ModBuspoll_TimeOut_check: true,
            ISCheck: true
        };

    }
    componentWillReceiveProps(nextProps) {
        this.setState({

            SPath: nextProps.serialcfg.SPath,
            IsOn: nextProps.serialcfg.IsOn != undefined
                ? nextProps.serialcfg.IsOn
                : false,
            Baudrate: nextProps.serialcfg.IsOn
                ? nextProps.serialcfg.Baudrate
                : '115200',
            Checkbit: nextProps.serialcfg.Checkbit
                ? nextProps.serialcfg.Checkbit
                : 'NONE',
            Databit: nextProps.serialcfg.Databit
                ? nextProps.serialcfg.Databit
                : "8",
            Stopbit: nextProps.serialcfg.Stopbit
                ? nextProps.serialcfg.Stopbit
                : "1",
            MaxLength: nextProps.serialcfg.MaxLength
                ? nextProps.serialcfg.MaxLength
                : "1024",
            Interval: nextProps.serialcfg.Interval
                ? nextProps.serialcfg.Interval
                : "20",
            SyncBaudrate: nextProps.serialcfg.SyncBaudrate != undefined
                ? nextProps.serialcfg.SyncBaudrate
                : false,
            ISHeartbeat: nextProps.serialcfg.ISHeartbeat != undefined
                ? nextProps.serialcfg.ISHeartbeat
                : false,
            Heartbeat_Hex: nextProps.serialcfg.Heartbeat_Hex
                ? nextProps.serialcfg.Heartbeat_Hex
                : "FF FF",
            Heartbeat_Interval: nextProps.serialcfg.Heartbeat_Interval
                ? nextProps.serialcfg.Heartbeat_Interval
                : "5000",
            Is_FullDuplex: nextProps.serialcfg.Is_FullDuplex != undefined
                ? nextProps.serialcfg.Is_FullDuplex
                : false,
            ServiceList: nextProps.serialcfg.ServiceList
                ? nextProps.serialcfg.ServiceList
                : [],
            Ismodbus: nextProps.serialcfg
                ? nextProps.serialcfg.Ismodbus
                : false, //模式是否是modbus
            ModBuspoll_TimeOut: nextProps.serialcfg
                ? nextProps.serialcfg.ModBuspoll_TimeOut
                : "150", //轮训时间间隔
            MaxLength_check: true,
            Interval_check: true,
            Heartbeat_Hex_check: true,
            Heartbeat_Interval_check: true,
            ModBuspoll_TimeOut_check: true,
            ISCheck: true
        });
    }
    //处理网络服务service的
    handleServiceCfg(msg: ServiceState, cmd?: string): boolean {
        console.log('cmd  ' + cmd);
        console.log(msg);
        if (cmd == "del") {
            let tmplist = this.state.ServiceList;
            tmplist.splice(msg.arrIndex, 1);
            this.setState({ ServiceList: tmplist });
            console.log(this.state);
            return;
        }

        if (msg.IsADD) {

            let tmplist = this.state.ServiceList;

            tmplist.push({

                IsOn: msg.IsOn,
                ServiceType: msg.ServiceType,
                NetNum: msg.NetNum,
                RemoteIP: msg.RemoteIP,
                IsspecifyPort: msg.IsspecifyPort,
                RemotePort: msg.RemotePort,
                LocalPort: msg.LocalPort,
                ISHeartbeat: msg.ISHeartbeat, //是否启用心跳包
                Heartbeat_Hex: msg.Heartbeat_Hex, //心跳包字节
                Heartbeat_Interval: msg.Heartbeat_Interval //心跳包间隔
            });
            this.setState({ ServiceList: tmplist });



        } else {
            let tmplist = this.state.ServiceList;

            tmplist[msg.arrIndex] = {
                IsOn: msg.IsOn,
                ServiceType: msg.ServiceType,
                NetNum: msg.NetNum,
                RemoteIP: msg.RemoteIP,
                IsspecifyPort: msg.IsspecifyPort,
                RemotePort: msg.RemotePort,
                LocalPort: msg.LocalPort,
                ISHeartbeat: msg.ISHeartbeat, //是否启用心跳包
                Heartbeat_Hex: msg.Heartbeat_Hex, //心跳包字节
                Heartbeat_Interval: msg.Heartbeat_Interval //心跳包间隔
            };
            this.setState({ ServiceList: tmplist });
        }

        return true;

    }
    mytest(str: string) {
        console.log("Serial" + str);
    }
    public handleClick(event: any): void {
        event.preventDefault();
        let name = event.currentTarget.name;
        if (name == "saveall") {

            MyCfg.mycfg.Serial_cfg[this.props.index] = this.state;
            console.log("保存结果:" + JSON.stringify(MyCfg.mycfg));
            let msgbox: any = this.refs.messagebox;
            //刷新显示有几个任务
            this
                .props
                .OnMessageSendEvent(this, 'nav', 'update');
            msgbox.Show();

        }
        else if (name == "quicksave") {
            MyCfg.mycfg.Serial_cfg[this.props.index] = this.state;
            for (let index = 0; index < MyCfg.mycfg.Serial_cfg.length; index++) {
                let oldcfg = MyCfg.mycfg.Serial_cfg[index];
                MyCfg.mycfg.Serial_cfg[index] = StringHelper.clone(this.state);
                MyCfg.mycfg.Serial_cfg[index].SPath = oldcfg.SPath;
                for (let sindex = 0; sindex < this.state.ServiceList.length; sindex++) {
                    let LocalPort: number = parseInt(this.state.ServiceList[sindex].LocalPort, 10);
                    if (LocalPort != 0) {
                        console.log(LocalPort + index);

                        MyCfg.mycfg.Serial_cfg[index].ServiceList[sindex].LocalPort = (LocalPort + index).toString();
                    }


                }
            }



            console.log("保存结果:" + JSON.stringify(MyCfg.mycfg));
            let msgbox: any = this.refs.messagebox;
            //刷新显示有几个任务
            this
                .props
                .OnMessageSendEvent(this, 'nav', 'update');
            msgbox.Show();
        }
    }
    public handleChange(event: any, namexxx: string): void {

        console.log(namexxx + "  " + event.target.value + "  " + event.target.checked);
        let tmp: SerialState = {};
        let _Isverifed: boolean = tmp[namexxx] = event.target.value;

        if (namexxx == "MaxLength" || namexxx == "Interval" || namexxx == "Heartbeat_Interval" || namexxx == "ModBuspoll_TimeOut") {
            tmp[namexxx + "_check"] = true;
            if (!StringHelper.IsInt(event.target.value)) {

                tmp[namexxx + "_check"] = false;
            }

        } else if (namexxx == "Heartbeat_Hex") {
            tmp[namexxx + "_check"] = true;
            if (!StringHelper.IsHex(event.target.value)) {

                tmp[namexxx + "_check"] = false;
            }
        }
        tmp[namexxx] = event.target.value;
        this.setState(tmp);
    }
    public handleChangeChecked(event: any, namexxx: string): void {
        console.log(event.target.nodeName);
        let tmp: SerialState = {};
        tmp[namexxx] = event.target.checked;
        this.setState(tmp);

    }
    public render(): JSX.Element {
        console.log("重新绘制串口配置界面");
        let _ischeck: boolean = false;
        if (this.state.Interval_check && this.state.Heartbeat_Hex_check && this.state.Heartbeat_Interval_check && this.state.MaxLength_check && this.state.ModBuspoll_TimeOut_check) {
            _ischeck = true;
        }
        var btns = [];
        if (this.props.index == 0) {
            btns.push(<button
                type="submit"
                name="quicksave"
                disabled={!_ischeck}
                className="btn btn-primary btn-lg  "
                onClick={e => this.handleClick(e)}>{Global.GetLocal("批量设置")}</button>);
            btns.push("   ");
        }


        let serviceviews = [];
        for (var index = 0; index < this.state.ServiceList.length; index++) {
            serviceviews.push(<Service
                CfgEvent={(msg, cmd) => this.handleServiceCfg(msg, cmd)}
                Servicefg={this.state.ServiceList[index]}
                arrIndex={index} />);

            if (index % 2 == 1) {
                serviceviews.push(
                    <div className="clearfix visible-sm"></div>
                );
            }
            if (index % 3 == 2) {
                serviceviews.push(
                    <div className="clearfix visible-lg"></div>
                );
            }

        }
        if (this.state.ServiceList.length < 5) { serviceviews.push(<Service CfgEvent={(msg, cmd) => this.handleServiceCfg(msg, cmd)} />); }

        //serviceviews.push(<Service CfgEvent={ this.handleServiceCfg}/>);
        let bg = this.state.IsOn
            ? ''
            : "bg-danger";
        //心跳包设置
        var xintiao: any;
        if (this.state.ISHeartbeat) {
            xintiao = <div>
                <div
                    className={this.state.Heartbeat_Interval_check
                        ? "form-group col-sm-7 "
                        : "form-group col-sm-7 has-error has-feedback"}>
                    <label className="col-xs-4 control-label">{Global.GetLocal("心跳包时间间隔")}
                    </label>
                    <div className="col-xs-8">
                        <input
                            type="text"
                            className="form-control "
                            placeholder=" "
                            value={this.state.Heartbeat_Interval}
                            onChange={e => this.handleChange(e, "Heartbeat_Interval")} />
                        <span
                            className={this.state.Heartbeat_Interval_check
                                ? "hidden"
                                : "glyphicon glyphicon-remove form-control-feedback"}></span>
                        <br
                            className={this.state.Heartbeat_Interval_check
                                ? "hidden"
                                : ""} />
                        <div
                            className={this.state.Heartbeat_Interval_check
                                ? "alert alert-danger hidden"
                                : "alert alert-danger "}
                            role="alert">{Global.GetLocal("请输入正确的数值")}</div>
                    </div>
                </div>
                <div
                    className={this.state.Heartbeat_Hex_check
                        ? "form-group col-sm-7 "
                        : "form-group col-sm-7 has-error has-feedback"}>
                    <label className="col-xs-4 control-label ">{Global.GetLocal("心跳包标识")}</label>
                    <div className="col-xs-8">
                        <input
                            type="text"
                            className="form-control"
                            placeholder=" "
                            value={this.state.Heartbeat_Hex}
                            onChange={e => this.handleChange(e, "Heartbeat_Hex")} />
                        <span
                            className={this.state.Heartbeat_Hex_check
                                ? "hidden"
                                : "glyphicon glyphicon-remove form-control-feedback"}></span>
                        <br
                            className={this.state.Heartbeat_Hex_check
                                ? "hidden"
                                : ""} />
                        <div
                            className={this.state.Heartbeat_Hex_check
                                ? "alert alert-danger hidden"
                                : "alert alert-danger "}
                            role="alert">{Global.GetLocal("请输入正确的标识")}</div>
                    </div>
                </div>
            </div >;

        }
        var modbusview: any;
        if (this.state.Ismodbus) {

            modbusview = <div
                className={this.state.ModBuspoll_TimeOut_check
                    ? "form-group col-sm-7 "
                    : "form-group col-sm-7 has-error has-feedback"}>
                <label className="col-xs-4 control-label">{Global.GetLocal("轮询时间")}</label>
                <div className="col-xs-8">
                    <input
                        type="text"
                        className="form-control"
                        placeholder=" "
                        value={this.state.ModBuspoll_TimeOut}
                        onChange={e => this.handleChange(e, "ModBuspoll_TimeOut")} />
                    <span
                        className={this.state.ModBuspoll_TimeOut_check
                            ? "hidden"
                            : "glyphicon glyphicon-remove form-control-feedback"}></span>
                    <br
                        className={this.state.ModBuspoll_TimeOut_check
                            ? "hidden"
                            : ""} />
                    <div
                        className={this.state.ModBuspoll_TimeOut_check
                            ? "alert alert-danger hidden"
                            : "alert alert-danger "}
                        role="alert">{Global.GetLocal("请输入正确的数值")}</div>
                </div>
            </div>
        }
        //波特率自适应
        var zhengwen: any;
        if (this.state.SyncBaudrate) {
            zhengwen = <div>


            </div>;
        }


        return (

            <div className="col-xs-12 col-sm-10  col-md-10 ">

                <div className="panel panel-default ">
                    <div className="panel-heading">
                        <h3 className="panel-title">
                            {`${Global.GetLocal("串口号") + (this.props.index + 1) + Global.GetLocal("参数设置")}`}

                            [{this.props.serialcfg.SPath}]</h3>
                    </div>
                    <div className={`panel-body ${bg}`}>
                        <MessageBox
                            ref="messagebox"
                            MessageType='alert'
                            Title={Global.GetLocal("提醒")}
                            Content={Global.GetLocal("保存配置成功")} />
                        <form className="form-horizontal " role="form">
                            <div className="form-group col-sm-7 ">

                                <label className="col-xs-4 control-label"></label>
                                <div className="col-xs-8 ">
                                    <label className="form-control input-lg  "><input
                                        type="checkbox"
                                        value='IsOn'
                                        checked={this.state.IsOn}
                                        onChange={e => this.handleChangeChecked(e, "IsOn")} />{Global.GetLocal("启用")}</label>

                                </div>
                            </div>
                            {/* <div className="form-group col-sm-7 ">

                                <label className="col-xs-4 control-label">工作模式</label>
                                <div className="col-xs-8">

                                    <label className="form-control  "><input
                                        type="checkbox"
                                        value='IsOn'
                                        checked={this.state.Is_FullDuplex}
                                        onChange={e => this.handleChangeChecked(e, "Is_FullDuplex")}/>全双工</label>

                                </div>
                            </div> */}
                            <div className="form-group col-sm-7" hidden={true}>
                                <label className="col-xs-4 control-label">{Global.GetLocal("自适应波特率")}</label>
                                <div className="col-xs-8">
                                    <label className="form-control  "><input
                                        type="checkbox"
                                        value='IsOn'
                                        checked={this.state.SyncBaudrate}
                                        onChange={e => this.handleChangeChecked(e, "SyncBaudrate")} />RFC2217</label>
                                </div>
                            </div>
                            <div >
                                <div className="form-group col-sm-7 ">

                                    <label className="col-xs-4 control-label">
                                        {Global.GetLocal("波特率")}
                                    </label>
                                    <div className="col-xs-8">

                                        <select
                                            className="form-control"
                                            onChange={e => this.handleChange(e, "Baudrate")}
                                            value={this.state.Baudrate}>
                                            <option>115200</option>
                                            <option>38400</option>
                                            <option>19200</option>
                                            <option>9600</option>
                                            <option>4800</option>
                                            <option>2400</option>
                                            <option>1200</option>
                                            <option>600</option>
                                            <option>300</option>
                                            <option>110</option>
                                        </select>

                                    </div>
                                </div>
                                <div className="form-group col-sm-7">
                                    <label className="col-xs-4 control-label">{Global.GetLocal("校验位")}</label>
                                    <div className="col-xs-8">
                                        <select
                                            className="form-control"
                                            onChange={e => this.handleChange(e, "Checkbit")}
                                            value={this.state.Checkbit}>
                                            <option>NONE</option>
                                            <option>ODD</option>
                                            <option>EVEN</option>
                                            <option>SPACE</option>
                                        </select>
                                    </div>
                                </div>
                                <div className="form-group col-sm-7 ">
                                    <label className="col-xs-4 control-label">{Global.GetLocal("数据位")}</label>
                                    <div className="col-xs-8">
                                        <select
                                            className="form-control"
                                            onChange={e => this.handleChange(e, "Databit")}
                                            value={this.state.Databit}>
                                            <option>8</option>
                                            <option>7</option>
                                            <option>6</option>
                                            <option>5</option>
                                        </select>
                                    </div>

                                </div>
                                <div className="form-group col-sm-7">
                                    <label className="col-xs-4 control-label">{Global.GetLocal("停止位")}</label>
                                    <div className="col-xs-8">
                                        <select
                                            className="form-control"
                                            onChange={e => this.handleChange(e, "Stopbit")}
                                            value={this.state.Stopbit}>
                                            <option>1</option>
                                            <option>2</option>
                                        </select>
                                    </div>
                                </div>
                                <div
                                    className={this.state.MaxLength_check
                                        ? "form-group col-sm-7 "
                                        : "form-group col-sm-7 has-error has-feedback"}>
                                    <label className="col-xs-4 control-label">{Global.GetLocal("最大包长度")}</label>
                                    <div className="col-xs-8">
                                        <input
                                            type="text"
                                            className="form-control"
                                            placeholder=" "
                                            value={this.state.MaxLength}
                                            onChange={e => this.handleChange(e, "MaxLength")} />

                                        <span
                                            className={this.state.MaxLength_check
                                                ? "hidden"
                                                : "glyphicon glyphicon-remove form-control-feedback"}></span>
                                        <br
                                            className={this.state.MaxLength_check
                                                ? "hidden"
                                                : ""} />
                                        <div
                                            className={this.state.MaxLength_check
                                                ? "alert alert-danger hidden"
                                                : "alert alert-danger "}
                                            role="alert">{Global.GetLocal("请输入正确的数值")}</div>
                                    </div>

                                </div>
                                <div
                                    className={this.state.Interval_check
                                        ? "form-group col-sm-7 "
                                        : "form-group col-sm-7 has-error has-feedback"}>
                                    <label className="col-xs-4 control-label">
                                        {Global.GetLocal("两包之间最小时间差")}
                                    </label>
                                    <div className="col-xs-8">
                                        <input
                                            type="text"
                                            className="form-control"
                                            placeholder=" "
                                            value={this.state.Interval}
                                            onChange={e => this.handleChange(e, "Interval")} />
                                        <span
                                            className={this.state.Interval_check
                                                ? "hidden"
                                                : "glyphicon glyphicon-remove form-control-feedback"}></span>
                                        <br
                                            className={this.state.Interval_check
                                                ? "hidden"
                                                : ""} />
                                        <div
                                            className={this.state.Interval_check
                                                ? "alert alert-danger hidden"
                                                : "alert alert-danger "}
                                            role="alert">{Global.GetLocal("请输入正确的数值")}</div>
                                    </div>
                                </div>


                                <div className="form-group col-sm-7">
                                    <label className="col-xs-4 control-label">{Global.GetLocal("心跳包")}</label>
                                    <div className="col-xs-8">
                                        <label className="form-control  "><input
                                            type="checkbox"
                                            value='IsOn'
                                            checked={this.state.ISHeartbeat}
                                            onChange={e => this.handleChangeChecked(e, "ISHeartbeat")} />{Global.GetLocal("启用")}</label>
                                    </div>

                                </div>
                                {xintiao}
                                <div className="form-group col-sm-7">
                                    <label className="col-xs-4 control-label">{Global.GetLocal("modbustcp")}</label>
                                    <div className="col-xs-8">
                                        <label className="form-control  "><input
                                            name="Ismodbus"
                                            type="checkbox"
                                            checked={this.state.Ismodbus}
                                            onChange={e => this.handleChangeChecked(e, "Ismodbus")} />{Global.GetLocal("启用")}</label>
                                    </div>

                                </div>
                                {modbusview}
                                <div className="form-group col-sm-12">

                                    <div className=" ">

                                        {serviceviews}

                                    </div>
                                </div>
                            </div>
                        </form>

                    </div>
                    <div className="panel-footer ">
                        <div className=" row width">
                            <div className=" center-block" style={{ width: '200px' }} >
                                {btns}
                                <button
                                    type="submit"
                                    name="saveall"
                                    disabled={!_ischeck}
                                    className="btn btn-primary btn-lg  "
                                    onClick={e => this.handleClick(e)}>{Global.GetLocal("保存")}</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div >
        )
    }
}
